package api

import (
	"gitee.com/gcom/stockdock/comm"
	"gitee.com/gcom/stockdock/core/job"
	"gitee.com/gcom/stockdock/core/router"
	s "gitee.com/gcom/stockdock/core/support"
	"gitee.com/gcom/stockdock/spider/ths"
	"net/http"
	"time"
)

func init() {
	router.AdminRouter.HandleFunc("/quote/updateHistThs", updateStockQuoteHistThs).Methods("GET")
	router.AdminRouter.HandleFunc("/quote/updateHistXq", updateStockQuoteHistXq).Methods("GET")
	router.AdminRouter.HandleFunc("/quote/updateQuoteThs", updateStockQuoteThs).Methods("GET")
	router.AdminRouter.HandleFunc("/quote/updateQuoteXq", updateStockQuoteXq).Methods("GET")
	router.ApiRouter.HandleFunc("/quote/dailyThs", dailyQuotesThs).Methods("GET")
}

func updateStockQuoteHistThs(w http.ResponseWriter, r *http.Request) {
	ctx := s.GetTracerCtx(w, r)
	job.JobThsQuoteHist.Run(ctx)
}

// 更新股票指标
func updateStockQuoteThs(w http.ResponseWriter, r *http.Request) {
	ctx := s.GetTracerCtx(w, r)
	job.JobThsQuote.Run(ctx)
}

// 更新股票历史日报价（雪球）
func updateStockQuoteHistXq(w http.ResponseWriter, r *http.Request) {
	ctx := s.GetTracerCtx(w, r)
	job.JobXqQuoteHist.Run(ctx)
}

func updateStockQuoteXq(w http.ResponseWriter, r *http.Request) {
	ctx := s.GetTracerCtx(w, r)
	job.JobXqQuote.Run(ctx)
}

// 查询股票日k线(同花顺)
func dailyQuotesThs(w http.ResponseWriter, r *http.Request) {
	ctx := s.GetTracerCtx(w, r)
	code := r.URL.Query().Get("code")
	if code == "" {
		s.ResFail(ctx, 400, "请指定股票代码")
		return
	}

	hist, err := ths.GetStockQuoteHistThs(ctx.DB, code)
	if err != nil {
		s.ResError(ctx, 500, err)
		return
	}
	daily, err := ths.GetStockThsDailyQuotes(ctx.DB, code)
	if err != nil {
		s.ResError(ctx, 500, err)
		return
	}

	var quotes = make([]*DailyQuote, len(hist), len(hist)+len(daily))
	for i, h := range hist {
		quotes[i] = &DailyQuote{
			Date:     h.Date,
			Open:     h.Open,
			High:     h.High,
			Low:      h.Low,
			Close:    h.Close,
			PreClose: h.PreClose,
			Volume:   h.Volume,
		}
	}
	var lastDate = comm.DefaultDateTime
	if len(quotes) > 0 {
		lastDate = quotes[len(quotes)-1].Date
	}
	for _, q := range quotes {
		if q.Date.Before(lastDate) {
			continue
		}
		quotes = append(quotes, &DailyQuote{
			Date:     q.Date,
			Open:     q.Open,
			High:     q.High,
			Low:      q.Low,
			Close:    q.Close,
			PreClose: q.PreClose,
			Volume:   q.Volume,
		})
	}
	s.ResOk(ctx, quotes)
}

type DailyQuote struct {
	Date     time.Time `json:"date"` // 报价日
	Open     float64   `json:"open"`
	High     float64   `json:"high"`
	Low      float64   `json:"low"`
	Close    float64   `json:"close"`
	PreClose float64   `json:"preClose"` // 昨日收盘价
	Volume   int64     `json:"volume"`
}
